﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Xww.IO {
    public class FilePreview {
        public int StartLine { get; set; }
        public int EndLine { get; set; }
        public bool IgnoreError { get; set; }
        public Encoding FileEncoding { get; set; }

        public FilePreview() {
            IgnoreError = true;
            FileEncoding = Encoding.Default;
            StartLine = 1; EndLine = 10;
        }
        public FilePreview(int start, int end, Encoding encoding)
            : this() {
            StartLine = start;
            EndLine = end;
            FileEncoding = encoding;
        }

        public string[] ReadLines(string filePath) {
            if (StartLine <= 0 || EndLine <= 0 || EndLine < StartLine) {
                throw new ArgumentOutOfRangeException("Start-End Position", "预览文件的起始结束位置不符合规则！");
            }
            List<string> list = new List<string>(EndLine - StartLine + 1);
            StreamReader reader  = null;
            if (FileEncoding == null) {
                reader = new StreamReader(filePath, true);
            }
            else {
                reader = new StreamReader(filePath, FileEncoding);
            }
            using ( reader ) {
                string line = null;
                int lineCount = 0;
                while (( line = reader.ReadLine())!= null) {
                    lineCount++;
                    if (lineCount < StartLine) { continue; }
                    if (lineCount > EndLine) { break; }
                    list.Add(line);
                }
                if ( !IgnoreError &&lineCount <= EndLine) {
                    throw new ArgumentOutOfRangeException("Line count",
                        string.Format("指定文件不存在 {0}-{1} 行", StartLine, EndLine));
                }
            }
            return list.ToArray();
        }

    }
}
